package com.apexsoft.front.common.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.apexsoft.front.common.plugins.filter.impl.CommonFilter;
import com.apexsoft.front.common.support.Result;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 根据IP地址获取详细的地域信息
 * 
 * @project:personGocheck
 * @class:AddressUtils.java
 * @author:heguanhua E-mail:37809893@qq.com
 * @date：Nov 14, 2012 6:38:25 PM
 */
public class AddressUtils {
    private static final Logger log  = LogManager.getRootLogger();
	/**
	 * 
	 * @param content
	 *            请求的参数 格式为：name=xxx&pwd=xxx
	 * @param encoding
	 *            服务器端请求编码。如GB2312,GBK,UTF-8等
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static JSONObject getAddresses()throws UnsupportedEncodingException {
		return getAddresses(getInternetIp());
	}
	/**
	 * 
	 * @param content
	 *            请求的参数 格式为：name=xxx&pwd=xxx
	 * @param encoding
	 *            服务器端请求编码。如GBK,UTF-8等
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static JSONObject getAddresses(String ip) throws UnsupportedEncodingException {
		JSONObject result = new JSONObject();
		result.put("success", false);
		result.put(Result.NOTE, "无效IP地址");
		// 这里调用淘宝的接口
		String urlStr = "http://ip.taobao.com/service/getIpInfo.php?ip="+ip;
		// 这里调用百度的IP查询地理位置API接口  ak密钥自己百度申请
		//urlStr = "http://api.map.baidu.com/location/ip?ak=59f8622bbb1bde0d3a930e96ea4b3945&ip="+ip+"&coor=bd09ll";
		String returnStr = GetIpDetails(urlStr,"GB2312");
		if (returnStr != null) {
			// 处理返回的省市区信息
			JSONObject rs = JSON.parseObject(returnStr);
			if (rs.getIntValue(Result.CODE)==1) {
				result.put("success", false);
				result.put(Result.NOTE, "无效IP地址");
			}else{
				rs = rs.getJSONObject("data");
				String area = decodeUnicode(rs.getString("area"));//地区
				String area_id = decodeUnicode(rs.getString("area_id"));//地区
				String country = decodeUnicode(rs.getString("country"));//国家
				String country_id = decodeUnicode(rs.getString("country_id"));//国家
				String region = decodeUnicode(rs.getString("region"));//省份
				String region_id = decodeUnicode(rs.getString("region_id"));//省份
				String city = decodeUnicode(rs.getString("city"));//市区 
				String city_id = decodeUnicode(rs.getString("city_id"));//市区 
				String county = decodeUnicode(rs.getString("county"));//区县
				String county_id = decodeUnicode(rs.getString("county_id"));//区县ID
				String isp = decodeUnicode(rs.getString("isp"));//ISP公司
				result.put("success", true);
				result.put(Result.NOTE, "IP地址获取成功！");
				result.put("GJ",country);
				result.put("GJ_ID",country_id);
				result.put("AREA",area);
				result.put("AREA_ID",area_id);
				result.put("PROVINCE",region);
				result.put("PROVINCE_ID",region_id);
				result.put("CITY",city);
				result.put("CITY_ID",city_id);
				result.put("SEC",county);
				result.put("SEC_ID",county_id);
				result.put("ISP",isp);
			}
		}
		return result;
	}
	public static JSONObject getPhoneInfo(String phone) throws UnsupportedEncodingException {
		//String url = "http://cz.115.com/?ct=index&ac=get_mobile_local&callback=apexsoft&action=mobile&mobile="+phone;
		String url = "http://api.showji.com/Locating/www.showji.co.m.aspx?m="+phone+"&output=json&callback=apexsoft";
		String line = AddressUtils.GetIpDetails(url,"UTF-8");
		//提取手机号码归属地的正则表达式   
        String REGEX_EXP="^apexsoft\\((.*)\\)$";   
        JSONObject sjjg = new JSONObject();
        sjjg.put("success", false);
    	sjjg.put(Result.NOTE, "手机号归属地查询失败！");
        //编译后的正则表达式Pattern对象   
        Pattern p = Pattern.compile(REGEX_EXP); 
        if(StringUtils.isNotBlank(line)){
        	//去掉line后面的;符号
    		line = line.replace(";", "");
	        Matcher m = p.matcher(line.trim());
	        if(m.matches()){   
		       	//System.out.println(m.group(1));
		       	JSONObject tem = JSON.parseObject(m.group(1));
		           if(tem!=null&&tem.getBooleanValue("QueryResult")){ 
		                sjjg.put("success", true);
		                sjjg.put(Result.NOTE, "手机号归属地查询成功！");
		                sjjg.put("province", tem.getString("Province"));//省份
		                sjjg.put("provincecode",tem.getString("AreaCode"));
		                sjjg.put("citycode",tem.getString("PostCode"));
		                sjjg.put("city", tem.getString("City"));//市区 
		                sjjg.put("corp", tem.getString("Corp"));//运营商
		           }
	        }
        }
		return sjjg;
	}
	
	/**
	 * 取内网IP地址
	 **/
	public static String getIntranetIp(HttpServletRequest request) {      
       String ip = request.getHeader("x-forwarded-for");      
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
           ip = request.getHeader("Proxy-Client-IP");      
       }      
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
           ip = request.getHeader("WL-Proxy-Client-IP");      
       }      
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
           ip = request.getRemoteAddr();      
       }      
       return ip;      
    } 
	/**
	 * 取公网IP地址
	 **/
	public static String getInternetIp() {      
       return GetIpDetails("http://iframe.ip138.com/ip2city.asp","GB2312");      
    } 
	
	/// <summary>         
    /// 得到真实IP以及所在地详细信息（Porschev）         
    /// </summary>         
    /// <returns></returns>         
    public static String GetIpDetails(String publicUrl,String encodingString) {  
    	String ip ="";
    	URLConnection conn = null ;
    	try {
    		 URL url = new URL(publicUrl);
		     conn = url.openConnection();
		     conn.setUseCaches(false);// 是否缓存true|false
		     conn.setRequestProperty("User-Agent",
		      "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15");
		     conn.setRequestProperty("Content-Type", "text/html");
		     conn.setRequestProperty("Accept",
		      "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		     InputStream is = conn.getInputStream();
		     BufferedReader reader = new BufferedReader(new InputStreamReader(is,encodingString));
		     String line = null;
		     StringBuffer buffer = new StringBuffer();
		     while ((line = reader.readLine()) != null) {
			      if (line.contains("您的IP地址是")) {
				       int start = line.indexOf('[') + 1;
				       int end = line.indexOf(']');
				       ip = line.substring(start, end);
				       buffer = new StringBuffer();
				       buffer.append(ip);
				       break;//获取到IP后终止循环
			      }else{
			    	  buffer.append(line);
			      }
		     }
		     reader.close();
		     return buffer.toString();
	  } catch (Exception e) {
		   // TODO: handle exception
		   e.printStackTrace();
	  }
	  return null;
    } 
    
	/* 测试
	@SuppressWarnings("static-access")
	public static void main(String[] args) {
		JSONObject address = new JSONObject();
		try {
			address = AddressUtils.getAddresses();
			System.out.println(getPhoneInfo("18605918862"));
			//JSONObject result = new JSONObject();
			// 这里调用百度的IP查询地理位置API接口  ak密钥自己百度申请
			//String urlStr = "http://api.map.baidu.com/location/ip?ak=59f8622bbb1bde0d3a930e96ea4b3945&ip="+ip+"&coor=bd09ll";
			//System.out.println(GetIpDetails(urlStr));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(address.toString());
		// 输出结果为：广东省,广州市,越秀区
	}
	*/
	/**
	 * unicode 转换成 中文
	 * 
	 * @author fanhui 2007-3-15
	 * @param theString
	 * @return
	 */
	public static String decodeUnicode(String theString) {
		char aChar;
		int len = theString.length();
		StringBuffer outBuffer = new StringBuffer(len);
		for (int x = 0; x < len;) {
			aChar = theString.charAt(x++);
			if (aChar == '\\') {
				aChar = theString.charAt(x++);
				if (aChar == 'u') {
					int value = 0;
					for (int i = 0; i < 4; i++) {
						aChar = theString.charAt(x++);
						switch (aChar) {
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException(
									"Malformed      encoding.");
						}
					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't') {
						aChar = '\t';
					} else if (aChar == 'r') {
						aChar = '\r';
					} else if (aChar == 'n') {
						aChar = '\n';
					} else if (aChar == 'f') {
						aChar = '\f';
					}
					outBuffer.append(aChar);
				}
			} else {
				outBuffer.append(aChar);
			}
		}
		return outBuffer.toString();
	}

	/**
	 * @throws UnsupportedEncodingException
	 *
	 * @Title: getRequestInputStream
	 * @Description: TODO(获取请求头信息)
	 * @param @param request
	 * @param @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	public JSONObject getRequestInputStream(HttpServletRequest request) throws UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
		JSONObject jObject = new JSONObject();
		jObject.put("msg", "post param seting...");
		try{
			// 读取请求内容
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while((line = br.readLine())!=null){
				sb.append(line);
			}
			// 将资料解码
			String reqBody = sb.toString();
			reqBody=  URLDecoder.decode(reqBody, "UTF-8");
			log.info("\n当前请求参数:"+reqBody);
			if(reqBody!=null&&!"".equals(reqBody))
				jObject = JSONObject.parseObject(reqBody);
		}catch (Exception e) {
		}
		return jObject;
	}
}
